<?php

class AuthController extends Zend_Controller_Action {

    public function init() {
        /* Initialize action controller here */
        $this->_auth = Zend_Auth::getInstance();
    }

    public function preDispatch() {
        if ($this->_auth->hasIdentity()) {
            if ($this->_request->getActionName() != 'logout') {
                $login = $this->_auth->getStorage()->read();
                if ($login->role != 'administrator') {
                    $this->_helper->redirector('userpage', 'user');
                } else {
                    $this->_helper->redirector('index', 'admin');
                }
            } else {
                parent::preDispatch();
            }
        } else {
            parent::preDispatch();
        }
    }

    public function indexAction() {
        $form = new APP_Form_Login();
        $request = $this->getRequest();
        if ($request->isPost()) {
            if ($form->isValid($request->getPost())) {
                if ($this->_process($form->getValues())) {
                    // We're authenticated! Redirect to the home page
                    $user = $this->_auth->getStorage()->read();
                    $this->_helper->FlashMessenger('Successful Login');

                    if ($user->role == 'member') {
                        if ($user->status == 0) {
                            $param = $this->getRequest()->getParam('param');
                            $token = (int) $param;
                            if ($user->salt == $token) {
                                $updateSlt = new Zend_Db_Table('login');
                                $updateSlt->update(array('status' => '1'), "email = '" . $_POST['email'] . "'");
                                $this->_helper->redirector('show', 'user');
                            }
                        } elseif ($user->status == 1) {
                            $this->_helper->redirector('userpage', 'user');
                        }
                    } elseif ($user->role == 'administrator') {
                        $this->_helper->redirector('index', 'admin');
                    }
                    //=========
                }
            }
        }

        $this->view->form = $form;
    }

    protected function _process($values) {

        $adapter = $this->_getAuthAdapter();
        $adapter->setIdentity($values['email']);
        $adapter->setCredential($values['password']);


        $result = $this->_auth->authenticate($adapter);
        Zend_Session::regenerateId();
        if ($result->isValid()) {
            $user = $adapter->getResultRowObject();
            $this->_auth->getStorage()->write($user);
            return true;
        }
        return false;
    }

    protected function _getAuthAdapter() {

        $dbAdapter = Zend_Db_Table::getDefaultAdapter();
        $authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);

        $authAdapter->setTableName('login')
                ->setIdentityColumn('email')
                ->setCredentialColumn('password')
                ->setCredentialTreatment('SHA1(CONCAT(?,salt))');

        return $authAdapter;
    }

    public function logoutAction() {
        // action body
        $session = new Zend_Session_Namespace('product');
        if (!empty($session->products)) {
            $bought = $session->products;
            $auth = Zend_Auth::getInstance();
            $login = $auth->getStorage()->read();
            $myuser = new Zend_Db_Table('users');
            $user = $myuser->fetchRow("email=" . "'" . $login->email . "'");

            foreach ($bought as $selected_product) {

                $products = new Zend_Db_Table('cart');
                $new = $products->createRow();
                $new->user_id = (int) $user['user_id'];
                $new->product_id = (int) $selected_product;
                $new->status = "in_process";
                $new->quantity = 1;
                $new->date = strftime("%G-%B-%e", strtotime("today"));
                $new->time = date("h:i:s A");
                $new->save();
            }
        }
        Zend_Session::namespaceUnset('product');
        $this->_auth->clearIdentity();
        $this->_helper->redirector('index'); // back to login page
    }

}

